package service

import (
	"apiserver/model"
	"sync"
	"apiserver/util"
)

func ListPost(UserId uint64, offset, limit int) ([]*model.PostInfo, uint64, error) {
	lists := make([]*model.PostInfo, 0)
	posts, count, err := model.GetPostList(UserId, offset, limit)
	if err != nil {
		return nil, count, err
	}
	ids := []uint64{}
	for _, post := range posts {
		ids = append(ids, post.Id)
	}
	wg := sync.WaitGroup{}
	postList := model.PostList{
		Lock:  new(sync.Mutex),
		IdMap: make(map[uint64]*model.PostInfo, len(posts)),
	}
	errChan := make(chan error, 1)
	finished := make(chan bool, 1)
	//并行处理数据
	for _, p := range posts {
		wg.Add(1)
		go func(p *model.PostModel) {
			defer wg.Done()
			shortId, err := util.GenShortId()
			if err != nil {
				errChan <- err
				return
			}
			postList.Lock.Lock()
			defer postList.Lock.Unlock()
			postList.IdMap[p.Id] = &model.PostInfo{
				Id:        p.Id,
				UserId:    p.UserId,
				Title:     p.Title,
				Content:   p.Content,
				ShortId:   shortId,
				CreatedAt: p.CreatedAt.Format("2006-01-02 15:04:05"),
				UpdatedAt: p.UpdatedAt.Format("2006-01-02 15:04:05"),
			}
		}(p)
	}
	go func() {
		wg.Wait()
		close(finished)
	}()
	select {
	case <-finished:
	case err := <-errChan:
		return nil, count, err
	}
	for _, id := range ids {
		lists = append(lists, postList.IdMap[id])
	}
	return lists, count, nil
}
